/**
 * 
 */
package com.flux.tms.tm${bean.numMain}web.modules.t${bean.numMain}${bean.numSub};

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.flux.tms.tm${bean.numMain}web.modules.t${bean.numMain}${bean.numSub}.service.${bean.javaFlieName}WebService;
import com.flux.scev6.appsecret.AppSecretService;
import com.flux.scev6.constant.CommonCVal;
import com.flux.scev6.dbopr.BaseDao;
import com.flux.scev6.dbopr.QueryHelper;
import com.flux.scev6.dbopr.dbhelper.DbHelper;
import com.flux.scev6.dbopr.model.ResultObj;
import com.flux.scev6.dbopr.query.pagequery.PageQueryDataSet;
import com.flux.scev6.function.functionhelper.BizHelper;
import com.flux.scev6.function.functionhelper.SFHelper;
import com.flux.scev6.importbiz.ImpFmFileCVal;
import com.flux.scev6.importbiz.impfmcsv.ImportFromCsvUtil;
import com.flux.scev6.importbiz.impfmexcel.ImportFromExcelUtil;
import com.flux.scev6.language.multilang.MultiLangHandler;
import com.flux.scev6.login.LoginInfoUtil;
import com.flux.scev6.login.model.LoginInfoObj;
import com.flux.scev6.privilege.ActionPrivCheckService;
import com.flux.scev6.rpc.hessian.api.IHessianClient;
import com.flux.scev6.rpc.rpc.RemoteServiceUtil;
import com.flux.scev6.udfquery.model.QrySqlObj;
import com.flux.scev6.utils.BizDataUtil;
import com.flux.scev6.utils.ResultObjUtil;
import com.flux.scev6.utils.datetime.DateFormatUtil;
import com.flux.scev6.utils.web.QueryStringUtil;
import com.flux.scev6.webservice.api.IJsonResult;
import com.flux.scev6.webservice.api.IWebLoginInfo;
import com.flux.scev6.webservice.impl.DefaultJsonResult;
import com.flux.scev6.webservice.impl.DefaultJsonWebService;
import org.springframework.stereotype.Component;

/**
 * 
 * T${bean.numMain}${bean.numSub} ${bean.notesMain} -- ${bean.notesSub}   -- web 控制层实现
 * 
 * T${bean.numMain}${bean.numSub} ${bean.notesSub}
 * 
 * <p>
 * 创建时间：${bean.dayTime}
 * <p>
 * 
 * <p>
 * 修改时间：${bean.dayTime}
 * <p>
 * 
 * @author ${bean.author}
 * 
 * @version V1.0.0
 *
 */
@Component("t${bean.numMain}${bean.numSub}_header")
public class ${bean.javaFlieName}1H extends DefaultJsonWebService {
	/*
	 * V100(${bean.numTime}) ${bean.author} 初版。
	 */

	@SuppressWarnings("unused")
	private static String verNum = "V100(${bean.numTime})";// 版本号

	@Autowired
	private ${bean.javaFlieName}WebService ${bean.javaFlieName}Service;
	@Autowired
	private AppSecretService appSecretService;
	@Autowired
	private IHessianClient hessianClient;
	@Autowired
	private RemoteServiceUtil remoteServiceUtil;
	@Autowired
	private ActionPrivCheckService actionPrivCheckService;

	/**
	 * ${bean.numSub} 表列表查询
	 *
	 * @author ${bean.author}
	 *
	 * @date ${bean.dayTime}
	 * 
	 * @param request
	 * @param response
	 * @param webLoginInfo
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	public IJsonResult getHeadersList(HttpServletRequest request, HttpServletResponse response,
			IWebLoginInfo webLoginInfo) throws IOException, ServletException {
		// ============================================================================
		// ============================================================================
		// ============================================================================
		DefaultJsonResult result = new DefaultJsonResult();
		// 获取登录信息对象
		LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${bean.javaFlieName}CVal.FUNC_ID);
		// 根据当前登录信息对象构造多语言处理器
		MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);
		try {
			//读写分离，设置数据源名称 -- 读从库
			BaseDao.setDataSourceName(CommonCVal.DS_SLAVEREAD);
			// 增加操作权限检查
			String[] actionIds = ${bean.javaFlieName}CVal.PRIVID_HEADER_QRY;
			boolean hasPrivilege = actionPrivCheckService.check(loginInfoObj,${bean.javaFlieName}CVal.FUNC_ID, actionIds);
			if (!hasPrivilege) {
				// 没有对应的操作权限
				String msg = mlh.getText(CommonCVal.ERRID_009);
				result.setErrMsg(msg);
				result.setOK(false);
				return result;
			}
			// 获取用户输入的查询条件
			Map<String, String> conditionMap = QueryStringUtil.getQueryStringMap(request);

			// //System.out.println("conditionMap:"+conditionMap);
			String otherReturnFields = getOtherRFs(loginInfoObj).toString();
			// //System.out.println("otherReturnFields:"+conditionMap);

			// 执行分页查询
			PageQueryDataSet pageQueryDataSet = ${bean.javaFlieName}Service.get${bean.javaFlieName}sListByPage(loginInfoObj, conditionMap,
					otherReturnFields);

			QueryHelper.processResultByPageQueryData(pageQueryDataSet, result, mlh, loginInfoObj);
		} catch (Exception ex) {
			ex.printStackTrace();
			String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的
			result.setErrMsg(msg);
			result.setOK(false);
		}
		return result;
		// ============================================================================
		// ============================================================================
		// ============================================================================
	}

	/**
	 * 其它的返回字段信息
	 *
	 * @author ${bean.author}  
	 *
	 * @date ${bean.dayTime}
	 * 
	 * @param loginInfoObj
	 * @return
	 */
	private StringBuffer getOtherRFs(LoginInfoObj loginInfoObj) {
	    // 获取不同类型数据库对应的helper
	    DbHelper dbHelper = ${bean.javaFlieName}Service.getDao().getDbHelper();
		String pattern = DateFormatUtil.getDateFormat(loginInfoObj); // 精确到天
		String pattern2 = DateFormatUtil.getFormat(loginInfoObj); // 精确到时分秒
	    StringBuffer otherRFs = new StringBuffer(100);
	<#list (bean.tableList)! as tableId>
		<#if (tableId)?contains("birthday")||(tableId)?contains("date")||(tableId)?contains("Date")||(tableId)?contains("Birthday")||(tableId)?contains("time")||(tableId)?contains("Time")>
		otherRFs.append(dbHelper.to_char("h1.${tableId}", pattern2)).append(" AS ${tableId}, ");
		<#else>
		otherRFs.append("h1.${tableId},");
		</#if>
	</#list>
		// udf
		otherRFs.append("h1.udf01,h1.udf02,h1.udf03,h1.udf04,h1.udf05,");
		otherRFs.append("h1.oprSeqFlag,");
		otherRFs.append("h1.addWho,");
		otherRFs.append("h1.noteText,");
		otherRFs.append("h1.currentVersion,");
		otherRFs.append("h1.editWho,");
		otherRFs.append(dbHelper.to_char("h1.addTime", pattern2)).append(" AS addTime, ");
		otherRFs.append(dbHelper.to_char("h1.editTime", pattern2)).append(" AS editTime ");
		return otherRFs;
	}

	/**
	 * 获取查询配置信息
	 *
	 * @author ${bean.author}  
	 *
	 * @date ${bean.dayTime}
	 * 
	 * @param request
	 * @param response
	 * @param webLoginInfo
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	public IJsonResult getQryTableList(HttpServletRequest request, HttpServletResponse response,
			IWebLoginInfo webLoginInfo) throws IOException, ServletException {
		// ============================================================================
		// ============================================================================
		// ============================================================================
		DefaultJsonResult result = new DefaultJsonResult();
		// 获取登录信息对象
		LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${bean.javaFlieName}CVal.FUNC_ID);
		// 根据当前登录信息对象构造多语言处理器
		MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);
		// ==============================================================================
		// ==============================================================================
		// ==============================================================================
		try {
			// 获取用户输入的查询条件
			Map<String, String> conditionMap = QueryStringUtil.getQueryStringMap(request);
			String otherReturnFields = getOtherRFs(loginInfoObj).toString();
			QrySqlObj qrySqlObj = new QrySqlObj(); // 表对象属性列表
			String queryName = "";

			// 获取查询列表名称
			if (conditionMap != null && conditionMap.size() > 0 && conditionMap.containsKey("queryName")) {
				queryName = conditionMap.get("queryName");
			}
			if (queryName.length() > 0) {
				qrySqlObj = ${bean.javaFlieName}Service.getQuerySql(loginInfoObj, conditionMap, otherReturnFields, false);
			}

			// 转JSON字符串返回
			if (qrySqlObj != null) {
				result.setBizJson(JSON.toJSONString(qrySqlObj));
			}
			result.setOK(true);

		} catch (Exception ex) {
			ex.printStackTrace();
			String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的
																									// 错误编号值
																									// 待完善
			result.setErrMsg(msg);
			result.setOK(false);
		}
		return result;
	}



	/**
	 * 保存头信息(新增、复制、编辑、删除)
	 *
	 * @author ${bean.author}  
	 *
	 * @date ${bean.dayTime}
	 * 
	 * @param request
	 * @param response
	 * @param webLoginInfo
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	public IJsonResult saveHeaderData(HttpServletRequest request, HttpServletResponse response,
			IWebLoginInfo webLoginInfo) throws IOException, ServletException {
		// ============================================================================
		// ============================================================================
		// ============================================================================
		DefaultJsonResult result = new DefaultJsonResult();
		// 获取登录信息对象
		LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${bean.javaFlieName}CVal.FUNC_ID);
		// 根据当前登录信息对象构造多语言处理器
		MultiLangHandler mlh = new MultiLangHandler(loginInfoObj);
		try {
			// 20171016 zhadc 设置数据源名称 -- 写主库
			BaseDao.setDataSourceName(CommonCVal.DS_MASTERWRITE);
			// 获取用户输入的数据
			Map<String, String> bizdataMap = QueryStringUtil.getQueryStringMap(request);
			// 检查操作标记
			boolean isContinue = false;
			String oprFlag = bizdataMap.get(CommonCVal.OPRFLAG);
			if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag) || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)
				|| CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)
				|| CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
				// =========================================================================
				isContinue = true;
			}
			if (!isContinue) {
				// 不支持的操作标记
				result.setErrMsg("EX91: not supported oprFlag");
				result.setOK(false);
				return result;
			}
			//增加操作权限检查 -- start --
			String[] actionIds = null;
			if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag) || CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)) {
				// 新增、复制
				actionIds = ${bean.javaFlieName}CVal.PRIVID_HEADER_ADD;
				// 日志分级、日志查询 时使用(这个信息会记录到 业务操作信息 和 系统SQL日志 中)。
				loginInfoObj.setActionId(${bean.javaFlieName}CVal.ACTION_ID_ADD);
			} else if (CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
				// 编辑
				actionIds = ${bean.javaFlieName}CVal.PRIVID_HEADER_EDT;
				// 日志分级、日志查询 时使用(这个信息会记录到 业务操作信息 和 系统SQL日志 中)。
				loginInfoObj.setActionId(${bean.javaFlieName}CVal.ACTION_ID_EDT);
			} else if (CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
				// 删除
				actionIds = ${bean.javaFlieName}CVal.PRIVID_HEADER_DEL;
				// 日志分级、日志查询 时使用(这个信息会记录到 业务操作信息 和 系统SQL日志 中)。
				loginInfoObj.setActionId(${bean.javaFlieName}CVal.ACTION_ID_DEL);
			}
			boolean hasPrivilege = actionPrivCheckService.check(loginInfoObj, ${bean.javaFlieName}CVal.FUNC_ID, actionIds);
			if (!hasPrivilege) {
				// 没有对应的操作权限
				String msg = mlh.getText(CommonCVal.ERRID_009);
				result.setErrMsg(msg);
				result.setOK(false);
				return result;
			}
			// 增加操作权限检查 -- end --
			bizdataMap.put(${bean.javaFlieName}CVal.KEYNAME_ORGANIZATIONID, loginInfoObj.getBizOrgId());

			// 组织输入参数，调用服务类准备
			String appSecret = appSecretService.getAppSecret();
			String loginInfo = LoginInfoUtil.toJSONString(loginInfoObj, appSecret);
			String bizData = BizDataUtil.toJSONString(bizdataMap, appSecret);
			String srvResult = null;

			// ==============================================================================
			// ==============================================================================
			// ==============================================================================
			if (remoteServiceUtil.isHessian()) {
				// 通过 Hessian 方式调用后端服务类程序
				// baseTariffServiceProvider 主表
				// baseTariffDetailServiceProvider 详情
				String clsId = "${bean.javaFlieName}ServiceProvider";
				String method = null;
				String version = "1.0.0";
				if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag)
						|| CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)) {
					// 新增、复制
					method = "add${bean.javaFlieName}";
				} else if (CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
					// 编辑
					method = "update${bean.javaFlieName}";
				} else if (CommonCVal.OPRFLAG_DEL.equalsIgnoreCase(oprFlag)) {
					// 删除
					method = "delete${bean.javaFlieName}";
				}
				srvResult = hessianClient.doAction(clsId, method, version, loginInfo, bizData);

				//System.out.println("isHessian" + srvResult);

			}
			
			// ==============================================================================
			// ==============================================================================
			// ==============================================================================
			// 处理服务类返回的结果信息
			ResultObj resultObj = ResultObjUtil.fromJSONString(srvResult, appSecret);
			if (resultObj.isCodeValueOK()) {

				// 使用服务类返回的主键值完成后续的操作。
				Map<String, String> conditionMap = new HashMap<String, String>();
				//自定义查询配置
				conditionMap.put("queryName", bizdataMap.get("queryName"));
				conditionMap.put(${bean.javaFlieName}CVal.KEYNAME_${(bean.pk01) ?upper_case}, resultObj.getPkey01());
				conditionMap.put(${bean.javaFlieName}CVal.KEYNAME_${(bean.pk02) ?upper_case}, resultObj.getPkey02());
	<#if (bean.pk03)!="">
				conditionMap.put(${bean.javaFlieName}CVal.KEYNAME_${(bean.pk03) ?upper_case}, resultObj.getPkey03());
	</#if><#if (bean.pk04)!="">
				conditionMap.put(${bean.javaFlieName}CVal.KEYNAME_${(bean.pk04) ?upper_case}, resultObj.getPkey04());
	</#if>
				// 查询最新的数据
				String bizJson = "[]";
				if (CommonCVal.OPRFLAG_ADD.equalsIgnoreCase(oprFlag)
						|| CommonCVal.OPRFLAG_COPY.equalsIgnoreCase(oprFlag)
						|| CommonCVal.OPRFLAG_EDIT.equalsIgnoreCase(oprFlag)) {
					// ===========================================
					String otherReturnFields = getOtherRFs(loginInfoObj).toString();
					// 执行查询
					PageQueryDataSet pageQueryDataSet = ${bean.javaFlieName}Service.get${bean.javaFlieName}sListByPage(loginInfoObj,
							conditionMap, otherReturnFields);
					SFHelper.processResultData_withOutPage(result, mlh, pageQueryDataSet);
					List<Map<String, Object>> rsData = pageQueryDataSet.getBizDataList();
					if(rsData!=null){
						String rsDataStr = JSON.toJSONString(rsData);
						result.setBizJson(rsDataStr);
						result.setOK(true);
					}else{
						String rsData2 = pageQueryDataSet.getBizData();
						result.setBizJson(rsData2);
						result.setOK(true);
					}
				} else {
					result.setBizJson(bizJson);
					result.setOK(true);
				}
			} else {
				// 错误处理 //把消息Id翻译成当前用户使用语言对应的文本描述
				 SFHelper.message_Error(${bean.javaFlieName}CVal.${bean.tableName},
				 mlh,result, resultObj);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			SFHelper.message_Exception(CommonCVal.ERRID_W100, mlh, result);
		}
		return result;
		// ============================================================================
		// ============================================================================
		// ============================================================================
	}

	/**
	 * 导入数据
	 *
	 * @author ${bean.author}  
	 *
	 * @date ${bean.dayTime}
	 * 
	 * @param request
	 * @param response
	 * @param webLoginInfo
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	public IJsonResult importData(HttpServletRequest request, HttpServletResponse response, IWebLoginInfo webLoginInfo)
			throws IOException, ServletException {
		
		
		//System.out.println("importData");
		// ============================================================================
		// ============================================================================
		// ============================================================================
		DefaultJsonResult result = new DefaultJsonResult();
		// 获取登录信息对象
		LoginInfoObj loginInfoObj = webLoginInfo.toLoginInfoObj(request, ${bean.javaFlieName}CVal.FUNC_ID);
		// 根据当前登录信息对象构造多语言处理器
		MultiLangHandler mlh = new MultiLangHandler(request, loginInfoObj);

		// 获取用户输入的查询条件
		Map<String, String> conditionMap = QueryStringUtil.getQueryStringMap(request);
		try {
			// 读写分离，设置数据源名称 -- V5WMS 写主库
			BaseDao.setDataSourceName(CommonCVal.DS_MASTERWRITE);

			String tableId = conditionMap.get("tableId");
			String fileType = conditionMap.get("fileType");
			String strMSGLTM = conditionMap.get("msgLtm");
			String currentSheetNo = conditionMap.get("sheetNo");
			String rowNoOfFieldName = conditionMap.get("fieldNo");
			String rowNoOfBeginDataRow = conditionMap.get("beginNo");
			String rowNoOfEndDataRow = conditionMap.get("endNo");
			String isContinueToNextRow = conditionMap.get("errorContinue");

			ImpHeaderFmExcelHelper impHelper = new ImpHeaderFmExcelHelper(request, loginInfoObj, ${bean.javaFlieName}CVal.FUNC_ID,
					tableId);

			impHelper.setstrMSGLTM(strMSGLTM);// 设置消息批次
			impHelper.setCurrentSheetNo(currentSheetNo);// 设置当前工作表编号
			impHelper.setRowNoOfFieldName(rowNoOfFieldName);// 设置字段名所在的行号
			impHelper.setRowNoOfBeginDataRow(rowNoOfBeginDataRow);// 设置开始数据行的行号
			impHelper.setRowNoOfEndDataRow(rowNoOfEndDataRow);// 设置结束数据行的行号
			impHelper.setisContinueToNextRow(isContinueToNextRow);// 设置当前行处理失败时是否继续处理下一行
		  //impHelper.setCroDetailCheck(true);
			// 执行逻辑
			if (ImpFmFileCVal.EXPORT_TYPE_XLSX.equalsIgnoreCase(fileType)
					|| ImpFmFileCVal.EXPORT_TYPE_XLS.equalsIgnoreCase(fileType)) {
				// Excel文件
				result = ImportFromExcelUtil.importData(impHelper);// 导入数据

			} else if (ImpFmFileCVal.EXPORT_TYPE_CSV.equalsIgnoreCase(fileType)) {
				// CSV文件
				result = ImportFromCsvUtil.importData(impHelper);// 导入数据
			}
			if (result == null) {
				result = new DefaultJsonResult();
				// 存放错误信息map
				Map<String, String> errorMap = new HashMap<String, String>();
				String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的
																										// 错误编号值
																										// 待完善
				errorMap.put("msg", msg);
				result.setExtra(JSON.toJSONString(errorMap));
				result.setOK(false);
				result.setState(false);
			}
		} catch (Exception ex) {
			// 存放错误信息map
			Map<String, String> errorMap = new HashMap<String, String>();
			ex.printStackTrace();
			String msg = mlh.getText(CommonCVal.ERRID_W100, new Object[] { CommonCVal.ERRID_W100 });// 这里的
																									// 错误编号值
																									// 待完善
			result.setErrMsg(msg);
			errorMap.put("msg", msg);
			result.setExtra(JSON.toJSONString(errorMap));
			result.setOK(false);
			result.setState(false);
		}
		// ============================================================================
		// ============================================================================
		// ============================================================================
		return result;
	}
}
